
import hashlib, random, string, requests
import json
from application import app


class MemberService():

    @staticmethod
    def geneAuthCode(member_info=None):
        # md5密钥
        m = hashlib.md5()
        str = ("{0}-{1}-{2}").format(member_info.id, member_info.salt,
                                         member_info.status)
        # 生成密钥
        m.update(str.encode("utf-8"))
        return m.hexdigest()

    @staticmethod
    def geneSalt( length = 16 ):
        keylist = [ random.choice( ( string.ascii_letters + string.digits ) ) for i in range( length ) ]
        return ( "".join( keylist ) )


    @staticmethod
    def getWechatOpenId(code):
        url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code" \
            .format(app.config['MINA_APP']['appid'], app.config['MINA_APP']['appsecret'], code)
        # 发起请求
        r = requests.get(url)
        res = json.loads(r.text)
        openid = None
        # 获取openid
        if 'openid' in res:
            openid = res['openid']
        return openid
